// web/src/app/api/(social)/messages/[id]/route.ts
import {NextRequest, NextResponse} from "next/server";
import {db} from "@/lib/db";
import {Relation} from '@prisma/client'

export async function GET(
    req: NextRequest,
    {params}: { params: { id: string } }
) {
    let id = params.id;
    try {
        const message = await db.message.findUnique({
            where: {id},
            include: {
                member: {
                    include: {
                        user: true
                    }
                },
                relation: {
                    include: {
                        RelationMemberIds: true
                    }
                }
            }
        })
        return NextResponse.json(message)
    } catch (e) {
        console.error(e)
        return new NextResponse('Internal Server Error', {status: 500});
    }
}

export async function DELETE(
    req: NextRequest,
    {params}: { params: { id: string } }
) {
    let id = params.id;
    try {
        const message = await db.message.delete({
            where: {id},
        })
        return NextResponse.json(message)
    } catch (e) {
        console.error(e)
        return new NextResponse('Internal Server Error', {status: 500});
    }
}

export async function PATCH(
    req: NextRequest,
    {params}: { params: { id: string } }
) {
    let id = params.id;
    const values = await req.json()
    console.log('update message', values)

    try {
        const message = await db.message.findUnique({
            where: {id},
            include: {
                member: {
                    include: {
                        user: true,
                    }
                },
                relation: {
                    include: {
                        // @ts-ignore
                        RelationMemberIds: true
                    }
                },
                reaction: true
            }
        })

        if (!message) return new NextResponse('Not Found', {status: 404});

        let updatedMessage

        if (values.relations) {
            // 删除原来的, 重新创建
            // for (let r of values.relations) {
            await db.relation.deleteMany({
                where: {messageId: id}
            })
            await db.relation.createMany({
                data: [
                    //@ts-ignore
                    ...(values.relations.map((item) => ({
                        value: item.value,
                        count: item.count,
                        messageId: id,
                    })))
                ]
            })
            // @ts-ignore
            for (const relation of values.relations) {
                const r = await db.relation.findFirst({
                    where: {
                        value: relation.value,
                        count: relation.count,
                        messageId: id,
                    }
                })

                await db.relationMemberIds.createMany({
                    data: [
                        // @ts-ignore
                        ...(relation.memberIds.map(m => {
                            return {
                                memberId: m,
                                // @ts-ignore
                                relationId: r.id,
                            }
                        }))
                    ]
                })
            }
            // }
        } else {
            updatedMessage = await db.message.update({
                where: {id},
                data: values
            })
        }
        return NextResponse.json(updatedMessage || message)
    } catch
        (e) {
        console.error(e)
        return new NextResponse('Internal Server Error', {status: 500});
    }
}